package core;

import model.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Store {
    /**
     * 管理员列表p
     */
    private static List<Admin> adminList;
    /**
     * 会员列表
     */
    private static List<Vip> vipList;
    /**
     * 商品列表
     */
    private static List<Goods> goodsList;

    /**
     * 商品分类
     */
    private static List<Category> categoryList;

    /**
     * 会员等级
     */
    private static List<Level> levelList;

    /**
     * 当前登录的用户
     */
    private Account currentUser;

    //静态初始化器
    static {

        vipList = new ArrayList<>(9);
        adminList = new ArrayList<>(1);
        goodsList = new ArrayList<>(5);
        categoryList = new ArrayList<>(3);
        levelList=new ArrayList<>( 5);
    }

    /**
     * Scanner对象
     * final修饰的变量叫常量，命名时每个单词都大写，单词间使用下划线（——）连接
     */
    private static final Scanner INPUT = new Scanner(System.in);

    //构造函数
    public Store() {
        //模拟已有数据
        Admin admin = new Admin("111", "111", "管理员");
        adminList.add(admin);


        //初始化
        categoryList.add(new Category(1001, "零食"));
        categoryList.add(new Category(1002, "蔬菜"));
        categoryList.add(new Category(1003, "水果"));
        categoryList.add(new Category(1004, "烟"));
        categoryList.add(new Category(1005, "酒"));

        goodsList.add(new Goods("1001","巧克力",7.8, 25.0,500,(Category)  categoryList.get(0)));
        goodsList.add(new Goods("1002","钟薛高",3.0,35,300,(Category) categoryList.get(0)));
        goodsList.add(new Goods("2001","蒜苔",5.5,55,700,(Category) categoryList.get(1)));
        goodsList.add(new Goods("2002","红萝卜",3.2,7.8,500,(Category) categoryList.get(1)));
        goodsList.add(new Goods("3001","增城挂绿",7.8,1049,600,(Category) categoryList.get(2)));
        goodsList.add(new Goods("3002","菠萝",5.8,980,300,(Category) categoryList.get(2)));
        goodsList.add(new Goods("4001","红塔山",55,70,800,(Category) categoryList.get(3)));
        goodsList.add(new Goods("4002","利群",36,360,750,(Category) categoryList.get(3)));
        goodsList.add(new Goods("4003","黄金叶",100,1000,50,(Category) categoryList.get(3)));
        goodsList.add(new Goods("5001","二锅头",25,35,5000,(Category) categoryList.get(4)));
        goodsList.add(new Goods("5002","金徽酒",650,700,400,(Category) categoryList.get(4)));
        goodsList.add(new Goods("5003","",520,600,500,(Category) category剑蓝春水晶剑List.get(4)));


        levelList.add(new Level("青铜会员",0,1));
        levelList.add(new Level("铂金会员",1000,0.99));
        levelList.add(new Level("白银会员",3000,0.95));
        levelList.add(new Level("黄金会员",6000,0.9));
        levelList.add(new Level("黑钻会员",10000,0.85));

        //模拟会员账号
        //模拟会员账号
        Vip vip = new Vip("222", "222", "王大锤",(Level)levelList.get(0));
        vipList.add(vip);
        vip = new Vip("333", "333", "9527",(Level)levelList.get(0));
        vipList.add(vip);


    }

    //类的方法
    public void open() {
        //打印欢迎语
        welcome();
        indexMenuList();
    }
    //welcome方法

    private void welcome() {
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        println("                                        ");
        println("               王大锤超市               ");
        println("                                        ");
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
        println("(请根据提示输入相应的编号使用本系统)");

    }

    /**
     * 首页功能
     */
    //indexMethod方法
    private void indexMenuList() {
        print("1、会员登录   ");
        print("2、注册   ");
        print("3、管理员登录  ");
        print("0、退出   ");
        print("请选择以上按钮：");
        int in = INPUT.nextInt();
        router(in);


    }

    /**
     * 管理员菜单
     */
    private void adminMenuList() {
        print("1、会员信息");
        print("2、商品入库");
        print("3、新增商品分类");
        print("4、商品列表");
        print("0、退出");
        print("请选择：");
        int in = INPUT.nextInt();
        //如果是0不变，如果不是 管理员路由 要加200
        if (in != 0) {
            in += 200;
        }
        router(in);
    }

    /**
     * 功能跳转
     *
     * @param in
     */
    private void router(int in) {
        switch (in) {
            case 1 -> login();
            case 2 -> register();
            case 3 -> adminLogin();
            case 201 -> showVipList();
            case 202 -> addGoods();
            case 203 -> addCategory();
            case 204 -> {
                showGoodsList();
                adminMenuList();
            }
            case 0 -> exit();
            default -> {
                print("输入错误，请重新输入：");
                router(INPUT.nextInt());
            }
        }
    }
    //商品列表展示

    private void showGoodsList() {
        println("商品列表如下：");
        //将currentUser强制转换为Vip类型
        if(currentUser instanceof Vip){
            //遍历goodlist菜单
            for(int i=0;i<goodsList.size();i++){
                //强制转换，获取goodelist中的元素
                Goods element=goodsList.get(i);
                //判断element的数是否大于0，大于0向会员展示商品信息
                if(element.getCount()>0){
                    println(element.show());
                }
            }
        }else{
            //向管理员展示商品信息
            println(goodsList.toString());
        }

    }

    //商品分类展示
    private void showCategory() {
        String categorys = categoryList.toString();
        println("现有商品分类如下：");
        if ("".equals(categorys)) {
            println("(暂无商品分类)");
        } else {
            println(categorys);
        }
    }
    //新增商品分类
    private void addCategory() {
        showCategory();
        println("请选择下一步：");
        print("1、继续添加商品         2、返回上一步");
        int t = INPUT.nextInt();
        if (t == 1) {
            print("请输入分类编号：");
            int no = INPUT.nextInt();
            print("请输入分类名称：");
            String name = INPUT.next();

            Category category = new Category(no, name);
            categoryList.add(category);
            adminMenuList();
        }else if(t==2){
            adminMenuList();
        }
    }
    /**
     * 商品入库
     */
    private void addGoods() {
        println("请选择下一步？");
        print("1、继续商品入库 2.返回上一步");
        int t = INPUT.nextInt();
        if (t == 1) {
            //判断选择为1时展示商品
            print("请输入商品编号：");
            String no = INPUT.next();
            Goods goods = null;
            //有没有保存
            for (int i = 0; i < goodsList.size(); i++) {
                Object element = goodsList.get(i);
                if (element instanceof Goods goods1) {
                    if (goods1.getGoodNo().equals(no)) {
                        goods = goods1;
                    }
                }

            }
            if (goods == null) {
                //新入库
                goods = new Goods();
                goods.setGoodNo(no);

                print("请输入商品名称：");
                String goodsName = INPUT.next();
                goods.setGoodsName(goodsName);

                print("请输入商品进价：");
                double cost = INPUT.nextDouble();
                goods.setCost(cost);

                print("请输入商品售价：");
                double price = INPUT.nextDouble();
                goods.setPrice(price);

                showCategory();
                int category = INPUT.nextInt();
                //遍历categoryList的数组
                for (int i = 0; i < categoryList.size(); i++) {
                    Object element = categoryList.get(i);

                    if (element instanceof Category category1) {
                        if (category1.getNo() == category) {
                            goods.setCategory(category1);
                            break;
                        }
                    }
                }
            }
            print("请输入商品数量：");
            int count = INPUT.nextInt();
            goods.setCount(goods.getCount() + count);

            goodsList.add(goods);
            println("添加商品成功！");
            adminMenuList();
        } else if (t==2) {
            adminMenuList();
        }
    }

    /**
     * 管理员登录
     */

    private void adminLogin() {
        print("请输入电话：");
        String phone = INPUT.next();
        print("请输入密码：");
        String password = INPUT.next();
        Admin login = new Admin(phone, password, null);
        Account flag = checkAccount(login,adminList);
        if (flag instanceof Admin admin) {
            login = admin;
        }
        if (flag != null) {
            //登录成功
            println(login.getName() + ",欢迎您来到管理员页面！");
            adminMenuList();
        } else {
            //失败
            println("账号或密码错误，请重试！");
            indexMenuList();
        }
    }

    /**
     * 检查账号是否正确
     *
     * @param list
     * @param account
     * @param vipList
     * @return
     */

    private Account checkAccount(Account account, List<Admin> list ) {
        for (int i = 0; i < list.size(); i++) {
            Object element = list.get(i);
            if (element instanceof Account account1) {
                if (account.login(account1)) {
                    return account1;
                }
            }
        }
        return null;
    }
    private Account checkAccount1(Account account, List<Vip> list ) {
        for (int i = 0; i < list.size(); i++) {
            Object element = list.get(i);
            if (element instanceof Account account1) {
                if (account.login(account1)) {
                    return account1;
                }
            }
        }
        return null;
    }
    //显示所有会员信息

    private void showVipList() {
        println("现在共有" + vipList.size() + "名会员，信息如下：");
        println(vipList.toString());
        println("请选择下一步：");
        print("1、上一步         2、返回首页");
        int t= INPUT.nextInt();
        if(t==1){
            //判断选择为1时展示商品
            adminMenuList();
        } else if (t==2) {

            indexMenuList();
        }
        return;
    }

    /**
     * 添加会员信息
     *
     * @param vip
     * @return
     */
    public static boolean addVip(Vip vip) {
        return vipList.add(vip);
    }

    /**
     * 退出系统
     */

    private void exit() {
        println("欢迎下次光临！");
        System.exit(0);
    }

    /**
     * 会员登录
     */
    private void login() {
        println("是否继续下一步？");
        print("1、继续登录         2、返回上一步");
        int t = INPUT.nextInt();
        if (t == 1) {
            print("请输入电话：");
            String phone = INPUT.next();
            print("请输入密码：");
            String password = INPUT.next();
            //创建
            Vip login = new Vip(phone, password, null);
            Account flag = checkAccount1(login, vipList);
            if (flag instanceof Vip vip) {
                login = vip;
            }
            if (flag != null) {
                currentUser = login;
                currentUser.setShopCar(new ArrayList<>(1));
                //登陆成功
                println(login.getName() + ",欢迎您！");
                println("是否展示商品？");
                print("1、展示商品         2、返回上一步");
                int a = INPUT.nextInt();
                if (a == 1) {
                    shopping();
                } else if (a==2) {
                    indexMenuList();
                }
                println("是否继续付款？");
                print("1、继续付款         2、返回菜单首页");
                int c = INPUT.nextInt();
                if (c == 1){
                    //结账
                    pay();
                }else{
                    indexMenuList();
                }

            } else {
                //失败
                println("账号或密码错误，请重试！");
                indexMenuList();
            }
        } else if (t==2) {
            indexMenuList();
        }
    }
    /**
     * 购物
     */
    private void shopping(){
        //展示所有货物
        showGoodsList();
        print("请选择您要购买的商品编号：");
        //TOOD(判断输入有效性)
        String no= INPUT.next();
        //输入想要购买商品的编号
        int index=goodsList.indexOf(new Goods(no));
        //（强制转换，向下转型）index是整个goodList的元素数组下标
        Goods goods=goodsList.get(index);

        print("请输入购买【"+goods.getGoodsName()+"】的数量：");
        //count数量
        int count= INPUT.nextInt();
        //判断库存够不够你需要的数量：count:想要买的数量，goods.getCount:商品库存
        while(goods.getCount()<count){
            //库存不够
            println("对不起，库存不够。请重新输入数量：");
            count= INPUT.nextInt();
        }
        //添加购物车:
        // currentUser:当前用户登录的信息：会员电话、密码、姓名、积分、余额、会员等级
        //goods是商品信息：名称、进价、售价、库存、分类
        // Treasure购物车

        currentUser.getShopCar().add(new Treasure(goods,count));
        println("是否继续购物？");
        print(" 1、继续购物          2、结账            3、返回菜单首页");
        int t= INPUT.nextInt();
        if(t==1){
            //判断选择为1时展示商品
            shopping();
        }else if(t==3){
            indexMenuList();
        }else{
            return;
        }
    }
    /**
     * 支付
     */
    private void pay(){
        println("您本次的购物清单是：");
        //调用Mylist中的当前用户消费卡
        ArrayList<Treasure> shopCar=currentUser.getShopCar();
        println("序号\t 商品名称 \t 单价 \t 数量 \t 小计");
        double sum=0;
        //遍历shopCar数组
        for (int i = 0; i < shopCar.size(); i++) {
            //向下转型，强制内型转换：Treasure--->shopCar
            Treasure element= shopCar.get(i);
            //总数
            sum +=element.getSum();
            println((i+1)+"\t"+element);

        }
        println("总计："+sum+"元");

        //in为会员价
        double in = sum;
        //将currentUser强制转换为vip类型
        if(currentUser instanceof Vip vip){
            //获取Vip的等级，调用访问方法
            Level level=vip.getLevel();
            in=level.getDiscount()*sum;
            println("您是尊贵的【"+level.getName()+"】"+"本次购物打折后应收："+in);
            double money=0.0;
            //判断给没给钱
            do{
                print("收款：");
                money= INPUT.nextDouble();
                //判断给的是否不够
                if(money<in){
                    println("付款金额不足，请重新支付！");
                }else{
                    break;
                }
            }while(true);
            println("找零："+(money-in));
            //修改商品库存
            for (int i = 0; i < shopCar.size(); i++) {
                //向下转型，强制内型转换，Treasure-->shopCar
                Treasure element =  shopCar.get(i);
                //调用get方法，获取商品库存数
                Goods goods = element.getGoods();
                //商品剩余总数=商品内存-顾客购买商品数
                goods.setCount(goods.getCount() - element.getNum());
            }
            //积分
            int point=(int)Math.floor(in);
            //积分数=原有积分+购买积分

            vip.setPoint(vip.getPoint()+point);

            //能否升级为会员
            for(int i= levelList.size()-1;i>=0;i--){
                Level element=levelList.get(i);
                if(element.getBase()<vip.getPoint()){
                    //符号当前等级
                    if(!element.getName().equals(vip.getLevel().getName())){
                        vip.setLevel(element);
                        println("恭喜您，升级为本店的【"+element.getName()+"】，以后购物可享"+(int)(element.getDiscount()*10)+"折");
                        break;
                    }
                    break;
                }
            }

        }
        logout();

    }

    private void logout() {
        println("欢迎下次光临！");
        currentUser=null;
        indexMenuList();
    }

    /**
     * 注册
     */
    public void register() {
        println("是否继续下一步？");
        print("1、继续注册         2、返回上一步");
        int t = INPUT.nextInt();
        if (t == 1) {
            println("注册：请根据提示输入会员信息");
            print("请输入手机号：");
            String phone = INPUT.next();
            //TODO校验是否已经注册
            //遍历会员数组的长度
            for (int i = 0; i < vipList.size(); i++) {
                //获取会员数组中的成员
                Object element = vipList.get(i);
                //向下玩转型，强制类型转换，将element类型转换为Vip类型，类型相同返回true,类型不同返回false
                if (element instanceof Vip vip) {
                    //引用数据类型相等的判断，判断输入的电话号码是否与Vip存的电话号码相同
                    if (phone.equals(vip.getPhone())) {
                        //相同输出提示
                        println("不好意思，手机号已经注册过了");
                        //返回菜单栏
                        indexMenuList();
                        break;
                    }
                }

            }


            //首先定义密码为空
            String pwd = null;
            //对输入的密码做循环判断
            do {
                print("请输入密码：");
                pwd = INPUT.next();
                print("请重新输入密码：");
                String pwd1 = INPUT.next();
                //两个密码不相等，重新输入密码
                if (!pwd.equals(pwd1)) {
                    System.out.println("您输入的密码错误，请重新输入！");
                } else {
                    //否则跳出循环
                    break;
                }
            } while (true);
            print("请输入会员姓名：");
            String name = INPUT.next();
            //将会员信息保存
            Vip vip = new Vip(phone, pwd, name);
            //调用添加函数进行会员的添加
            addVip(vip);
            println(name + ",恭喜您成为会员！");
            //回到上一级
            indexMenuList();
        } else if (t==2) {
            indexMenuList();

        }
    }


    /**
     * 控制台打印封装
     */
    //静态方法
    public static void println(String str) {
        System.out.println(str);
    }

    public static void print(String str) {
        System.out.println(str);
    }


}

